package demo.pattern.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

// 单例模式：饿汉实现
public class StarvingSingleton {
    private static final StarvingSingleton starvingSingleton = new StarvingSingleton();
    private StarvingSingleton(){ }
    public static StarvingSingleton getInstance(){
        return starvingSingleton;
    }

	public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
		System.out.println(starvingSingleton.getInstance());
		System.out.println(starvingSingleton.getInstance());
		// 可以通过反射获取构造函数，创建新的对象，破坏饿汉单例模式
		Class clazz = StarvingSingleton.class;
		Constructor constructor = clazz.getDeclaredConstructor();
		constructor.setAccessible(true);
		System.out.println(constructor.newInstance());
	}

}

